import {Button, Checkbox, Input, Modal, Pagination, Tooltip} from "antd";
import {useEffect, useState} from "react";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import useMessage from "antd/es/message/useMessage";

/**
 * 角色列表查询模态框
 *
 * @returns {JSX.Element}
 * @constructor
 */
const RoleList = (props) => {

    const {
        roleListModalVisible,
        setRoleListModalVisible,
        allocateRoles,  // 从props传来的已选中角色
        setAllocateRoles
    } = props;

    const [messageApi, contextHolder] = useMessage();
    // 选中的角色（与props.allocateRoles保持同步，基于roleName）
    const [roles, setRoles] = useState([]);
    // 角色查询条件
    const [pageRoleReq, setPageRoleReq] = useState({
        roleName: '',
        roleDescription: ''
    });
    // 分页查询参数（默认每页18条）
    const [paginationReq, setPaginationReq] = useState({
        pageNum: 1,
        pageSize: 18
    });
    // 角色查询结果
    const [pageQueryRoleResp, setPageQueryRoleResp] = useState({
        total: 0,
        pageCount: 1,
        records: []
    });

    /**
     * 分页查询系统角色
     */
    const pageQuerySysRole = () => {
        RequestUtils.post(RequestApis.roleManage.page, {
            ...pageRoleReq,
            ...paginationReq
        }).then(res => {
            setPageQueryRoleResp(res.data.data || {total: 0, pageCount: 1, records: []});
        }).catch(err => messageApi.error(err.message || '角色查询失败'));
    };

    /**
     * 初始化/更新选中的角色（基于roleName同步并去重）
     */
    useEffect(() => {
        // 同步并基于roleName去重，确保无重复角色
        const uniqueRoles = Array.from(new Map(allocateRoles.map(role => [role.roleName, role])).values());
        setRoles(uniqueRoles);

        // 重置查询条件
        setPageRoleReq({
            roleName: '',
            roleDescription: ''
        });

        // 打开模态框时查询角色列表
        if (roleListModalVisible) {
            setPaginationReq(prev => ({...prev, pageNum: 1})); // 重置为第一页
            pageQuerySysRole();
        }
        // eslint-disable-next-line
    }, [roleListModalVisible, allocateRoles]);

    /**
     * 分页条件改变后立即查询
     */
    useEffect(() => {
        if (roleListModalVisible) { // 仅在模态框打开时查询
            pageQuerySysRole();
        }
        // eslint-disable-next-line
    }, [paginationReq, roleListModalVisible]);

    // 检查角色是否已被选中（基于roleName精准匹配）
    const isRoleSelected = (targetRoleName) => {
        return roles.some(role => role.roleName === targetRoleName);
    };

    // 切换角色选择状态（基于roleName，添加时去重）
    const toggleRoleSelection = (role) => {
        const targetRoleName = role.roleName;
        if (isRoleSelected(targetRoleName)) {
            // 取消选中：过滤掉对应roleName的角色
            const newRoles = roles.filter(item => item.roleName !== targetRoleName);
            setRoles(newRoles);
        } else {
            // 新增选中：基于roleName去重后添加
            const newRoles = [...roles, role];
            const uniqueNewRoles = Array.from(new Map(newRoles.map(r => [r.roleName, r])).values());
            setRoles(uniqueNewRoles);
        }
    };

    // 确认选择（基于roleName最终去重）
    const confirmSelection = () => {
        const uniqueRoles = Array.from(new Map(roles.map(role => [role.roleName, role])).values());
        setAllocateRoles(uniqueRoles.map(role => ({
            roleId: role.id,
            roleName: role.roleName,
            roleDescription: role.roleDescription
        })));
        setRoleListModalVisible(false);
    };

    // 处理分页变化（页码改变时触发，每页条数固定为18）
    const handlePaginationChange = (page) => {
        setPaginationReq({
            ...paginationReq,
            pageNum: page
        });
    };

    return (
        <Modal
            open={roleListModalVisible}
            title="选择角色"
            width={900}
            onCancel={() => setRoleListModalVisible(false)}
            footer={
                <div style={{
                    display: 'flex',
                    justifyContent: 'flex-end',
                    gap: 12,
                    padding: '16px 24px',
                    backgroundColor: '#f8fafc'
                }}>
                    <Button
                        type={"primary"}
                        onClick={confirmSelection}
                        size="middle"
                    >
                        确认
                    </Button>
                    <Button
                        danger={true}
                        onClick={() => setRoleListModalVisible(false)}
                        size="middle"
                    >
                        取消
                    </Button>
                </div>
            }
            style={{
                borderRadius: 20,
                overflow: 'hidden',
                boxShadow: '0 20px 60px rgba(0, 0, 0, 0.15)'
            }}
            bodyStyle={{
                padding: 0,
                backgroundColor: '#f8fafc',
                maxHeight: 600,
                overflow: 'hidden'
            }}
            titleStyle={{
                fontSize: 18,
                fontWeight: 600,
                color: '#1f2937',
                padding: '20px 24px 0 24px'
            }}
            maskClosable={false}
        >
            <div style={{
                backgroundColor: '#ffffff',
                borderRadius: 16,
                padding: 24,
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)'
            }}>
                {contextHolder}

                {/* 搜索区域 */}
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 16,
                    marginBottom: 20,
                    flexWrap: 'wrap',
                    padding: '16px',
                    backgroundColor: '#f8fafc',
                    borderRadius: 12,
                    border: '1px solid #e2e8f0'
                }}>
                    <div style={{display: 'flex', alignItems: 'center', gap: 12, flex: 1, minWidth: 250}}>
                        <span style={{
                            fontSize: 14,
                            color: '#4b5563',
                            whiteSpace: 'nowrap',
                            fontWeight: 500
                        }}>角色名：</span>
                        <Input
                            value={pageRoleReq.roleName}
                            onChange={(e) => {
                                setPageRoleReq({
                                    ...pageRoleReq,
                                    roleName: e.target.value
                                })
                            }}
                            size="middle"
                            style={{
                                flex: 1,
                                height: 40,
                                borderRadius: 10,
                                fontSize: 14,
                                border: '2px solid #e2e8f0',
                                transition: 'all 0.3s ease'
                            }}
                            onMouseEnter={(e) => {
                                e.target.style.borderColor = '#cbd5e1';
                            }}
                            onMouseLeave={(e) => {
                                e.target.style.borderColor = '#e2e8f0';
                            }}
                            placeholder="请输入角色名"
                        />
                    </div>

                    <div style={{display: 'flex', gap: 12}}>
                        <Button
                            type={'primary'}
                            onClick={pageQuerySysRole}
                            size="middle"
                            style={{
                                height: 40,
                                borderRadius: 10,
                                padding: '0 24px',
                                fontSize: 14,
                                fontWeight: 500,
                                backgroundColor: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                                border: 'none',
                                boxShadow: '0 4px 12px rgba(79, 172, 254, 0.3)'
                            }}
                            onMouseEnter={(e) => {
                                e.target.style.background = 'linear-gradient(135deg, #00f2fe 0%, #4facfe 100%)';
                                e.target.style.transform = 'translateY(-2px)';
                                e.target.style.boxShadow = '0 6px 16px rgba(79, 172, 254, 0.4)';
                            }}
                            onMouseLeave={(e) => {
                                e.target.style.background = 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)';
                                e.target.style.transform = 'translateY(0)';
                                e.target.style.boxShadow = '0 4px 12px rgba(79, 172, 254, 0.3)';
                            }}
                        >
                            查询
                        </Button>
                        <Button
                            danger={true}
                            onClick={() => {
                                setPageRoleReq({
                                    roleName: '',
                                    roleDescription: ''
                                });
                                setPaginationReq(prev => ({...prev, pageNum: 1}));
                                pageQuerySysRole();
                            }}
                            size="middle"
                            style={{
                                height: 40,
                                borderRadius: 10,
                                padding: '0 24px',
                                fontSize: 14,
                                fontWeight: 500,
                                backgroundColor: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
                                border: 'none',
                                boxShadow: '0 4px 12px rgba(250, 112, 154, 0.3)'
                            }}
                            onMouseEnter={(e) => {
                                e.target.style.background = 'linear-gradient(135deg, #fee140 0%, #fa709a 100%)';
                                e.target.style.transform = 'translateY(-2px)';
                                e.target.style.boxShadow = '0 6px 16px rgba(250, 112, 154, 0.4)';
                            }}
                            onMouseLeave={(e) => {
                                e.target.style.background = 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)';
                                e.target.style.transform = 'translateY(0)';
                                e.target.style.boxShadow = '0 4px 12px rgba(250, 112, 154, 0.3)';
                            }}
                        >
                            清空
                        </Button>
                    </div>
                </div>

                {/* 角色列表区域 - 基于roleName自动勾选已选中角色 */}
                <div style={{
                    flex: 1,
                    overflowY: 'auto',
                    padding: '12px',
                    borderRadius: 12,
                    backgroundColor: '#f8fafc',
                    border: '1px solid #e2e8f0'
                }}>
                    {pageQueryRoleResp.records && pageQueryRoleResp.records.length > 0 ? (
                        <div style={{
                            display: 'grid',
                            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
                            gap: 20,
                            padding: '8px 4px'
                        }}>
                            {pageQueryRoleResp.records.map(v => {
                                const selected = isRoleSelected(v.roleName); // 基于roleName判断选中状态
                                return (
                                    <Tooltip
                                        title={v.roleDescription || '无描述信息'}
                                        color={'#722ed1'}
                                        key={v.roleName} // 用roleName作为key（确保唯一）
                                        placement="top"
                                        mouseEnterDelay={0.2}
                                    >
                                        <div
                                            onClick={() => toggleRoleSelection(v)}
                                            style={{
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: 12,
                                                padding: 16,
                                                backgroundColor: selected ? '#e6f7ff' : '#ffffff',
                                                border: `2px solid ${selected ? '#1890ff' : '#e2e8f0'}`,
                                                borderRadius: 12,
                                                cursor: 'pointer',
                                                transition: 'all 0.3s ease',
                                                boxShadow: selected ? '0 4px 12px rgba(24, 144, 255, 0.15)' : '0 2px 8px rgba(0, 0, 0, 0.05)'
                                            }}
                                            onMouseEnter={(e) => {
                                                e.target.style.transform = 'translateY(-3px)';
                                                e.target.style.boxShadow = selected ?
                                                    '0 8px 20px rgba(24, 144, 255, 0.25)' :
                                                    '0 6px 16px rgba(0, 0, 0, 0.1)';
                                                e.target.style.borderColor = selected ? '#1890ff' : '#cbd5e1';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.target.style.transform = 'translateY(0)';
                                                e.target.style.boxShadow = selected ?
                                                    '0 4px 12px rgba(24, 144, 255, 0.15)' :
                                                    '0 2px 8px rgba(0, 0, 0, 0.05)';
                                                e.target.style.borderColor = selected ? '#1890ff' : '#e2e8f0';
                                            }}
                                        >
                                            <Checkbox
                                                checked={selected} // 自动勾选已选中角色
                                                size="middle"
                                                style={{margin: 0}}
                                                onChange={(e) => {
                                                    e.stopPropagation();
                                                    toggleRoleSelection(v);
                                                }}
                                            />
                                            <span style={{
                                                fontSize: 14,
                                                color: '#1f2937',
                                                whiteSpace: 'nowrap',
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                flex: 1,
                                                fontWeight: 500
                                            }}>
                                                {v.roleName}
                                            </span>
                                        </div>
                                    </Tooltip>
                                );
                            })}
                        </div>
                    ) : (
                        <div style={{
                            width: '100%',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            height: 300,
                            color: '#9ca3af',
                            fontSize: 14,
                            flexDirection: 'column',
                            gap: 8,
                            backgroundColor: '#f8fafc',
                            borderRadius: 12,
                            border: '1px dashed #e2e8f0'
                        }}>
                            <span style={{fontSize: 16, fontWeight: 500}}>暂无角色数据</span>
                            <span style={{fontSize: 12, color: '#6b7280'}}>请调整查询条件后重试</span>
                        </div>
                    )}
                </div>

                {/* 分页控件（只提供18条/页） */}
                {pageQueryRoleResp.total > 0 && (
                    <div style={{
                        marginTop: 20,
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        paddingTop: 16,
                        borderTop: '2px solid #e2e8f0'
                    }}>
                        <div style={{
                            fontSize: 14,
                            color: '#6b7280'
                        }}>
                            已选：<span style={{color: '#667eea', fontWeight: 600}}>{roles.length}</span> 个角色
                        </div>
                        <Pagination
                            current={paginationReq.pageNum} // 当前页码
                            pageSize={paginationReq.pageSize} // 固定每页18条
                            total={pageQueryRoleResp.total} // 总条数
                            pageSizeOptions={['18']} // 仅保留18条选项
                            showSizeChanger={false} // 隐藏每页条数切换（可选，若想显示固定选项可设为true）
                            showQuickJumper // 显示快速跳转
                            showTotal={(total) => `共 ${total} 条，每页18条`} // 显示总条数和每页固定条数说明
                            onChange={handlePaginationChange} // 仅处理页码变化
                            size="middle" // 中等尺寸，适配整体风格
                            style={{fontSize: 13}}
                        />
                    </div>
                )}

                {/* 底部信息（当无数据时显示） */}
                {pageQueryRoleResp.total === 0 && (
                    <div style={{
                        marginTop: 20,
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        fontSize: 14,
                        color: '#6b7280',
                        paddingTop: 16,
                        borderTop: '2px solid #e2e8f0'
                    }}>
                        <span>已选：<span style={{color: '#667eea', fontWeight: 600}}>{roles.length}</span> 个角色</span>
                        <span>共 0 个角色</span>
                    </div>
                )}
            </div>
        </Modal>
    );
};

export default RoleList;



